//
//  WelcomeViewController.swift
//  SinaWeibo
//
//  Created by 胡阳 on 16/5/30.
//  Copyright © 2016年 young4ever. All rights reserved.
//

import UIKit
import SDWebImage

class WelcomeViewController: UIViewController {

    /// 记录底部约束
    var bottomConstraint : NSLayoutConstraint?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        print(#function)
        // 1.添加子控件
        view.addSubview(bgView)
        view.addSubview(avatorView)
        view.addSubview(msgLabel)
        
        // 2.布局子控件
        bgView.xmg_Fill(view)
        
        let cons = avatorView.xmg_AlignInner(type: XMG_AlignType.BottomCenter, referView: view, size: CGSizeMake(100, 100), offset: CGPointMake(0, -150))
        // 2.1 拿到底部约束
        bottomConstraint = avatorView.xmg_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        msgLabel.xmg_AlignHorizontal(type: XMG_AlignType.BottomCenter, referView: avatorView, size: nil, offset: CGPointMake(0, 20))
        
        // 3.加载头像
        if let url = UserAccount.loadAccount()?.avatar_large {
            avatorView.sd_setImageWithURL(NSURL(string: url))
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
//        print(bottomConstraint?.constant)
        bottomConstraint?.constant = -UIScreen.mainScreen().bounds.height - bottomConstraint!.constant
//        print(bottomConstraint?.constant)

        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue()) {
            
            UIView.animateWithDuration(2, animations: {
                
                self.avatorView.layoutIfNeeded()
                
            }) { (_) in
                
                // 文本动画
                UIView.animateWithDuration(2.0, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: UIViewAnimationOptions(rawValue: 0), animations: {
                    self.msgLabel.alpha = 1.0
                    }, completion: { (_) in
//                        print("msgLabel animation completed")
                        // 去主页
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: true)
                })
            }
        }
    }

    // MARK: - 懒加载
    private lazy var bgView : UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    
    private lazy var avatorView : UIImageView = {
    
        let iv = UIImageView(image: UIImage(named: "avatar_default_big"))
        iv.layer.cornerRadius = 50
        iv.clipsToBounds = true
        return iv
    }()
    
    private lazy var msgLabel : UILabel = {
    
        let label = UILabel()
        label.text = "欢迎回来"
        label.alpha = 0
        label.sizeToFit()
        return label
    }()
}
